package cn.imvc.app.controllers.goods;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import cn.imvc.app.entities.Goods;
import cn.imvc.app.entities.GoodsSku;
import cn.imvc.app.entities.GoodsSpec;
import cn.imvc.app.entities.GoodsSpecValue;
import cn.imvc.app.entities.InventoryFlow;
import cn.imvc.app.models.GoodsModel;
import cn.imvc.app.models.GoodsSkuModel;
import cn.imvc.app.models.GoodsSpecModel;
import cn.imvc.app.models.GoodsSpecValueModel;
import cn.imvc.app.models.LoggingModel;
import cn.imvc.core.DialogBean;
import cn.imvc.core.Render;
import cn.imvc.data.domain.ViewRequest;

public class GoodsSkuControllerImpl implements GoodsSkuController{
	static Logger logger = Logger.getLogger(GoodsSkuControllerImpl.class);
	@Autowired
	GoodsSkuModel goodsSkuModel;
	@Autowired
	GoodsModel goodsModel;
	@Autowired
	GoodsSpecModel goodsSpecModel;
	@Autowired
	GoodsSpecValueModel goodsSpecValueModel;
	@Autowired
	LoggingModel loggingModel;
	
	public int goodsId;
	public int id;
	public int[] ids;
	public GoodsSku goodsSku;
	public List<GoodsSku> goodsSkus;
	public List<GoodsSpec> goodsSpecs;
	public List<GoodsSpecValue> goodsSpecValues;
	public List<List<GoodsSpecValue>> lists;
	public Page<GoodsSku> page;
	public ViewRequest viewRequest;
	public String[] specName;
	public String[] specId;
	public InventoryFlow inventoryFlow;
	public String specIdStr;
	public String isFree;
	public String isLock;
	private String multipleDialogMyIds;
	private String multipleDialogMyNames;
	
	
	public String search() {
		// TODO Auto-generated method stub
		return null;
	}

	public String index() {
		
//		Goods goods = goodsModel.get(goodsId);
//		goodsSkus = goodsSkuModel.findByGoods(goods);
//		goodsSpecs = goodsSpecModel.findByGoods(goods);
//		lists = new ArrayList<List<GoodsSpecValue>>();
//		goodsSpecValueModel.Descartes(goodsSpecs, lists, 0, new ArrayList<GoodsSpecValue>());
		Map<String, String> searchMap = new HashMap<String, String>();
		searchMap.put("goodsId_eq_string", String.valueOf(goodsId));
		viewRequest = new ViewRequest();
		viewRequest.setParams(searchMap);
		page=goodsSkuModel.find(viewRequest);
		return "goods-sku/index";
	}

	public String show() {
		// TODO Auto-generated method stub
		return null;
	}

	public String editNew() {
		Goods goods = goodsModel.get(goodsId);
		goodsSpecValues = new ArrayList<GoodsSpecValue>();
		goodsSpecs = goodsSpecModel.findByGoods(goods);
		Iterator<GoodsSpec> iterator = goodsSpecs.iterator();
		while (iterator.hasNext()) {
			GoodsSpec goodsSpec = (GoodsSpec) iterator.next();
			Iterator<GoodsSpecValue> specValueIterator = goodsSpec.getGoodsSpecValue().iterator();
			while (specValueIterator.hasNext()) {
				GoodsSpecValue goodsSpecValue = (GoodsSpecValue) specValueIterator.next();
				goodsSpecValue.setId(0);
				goodsSpecValue.setSpecName("");
				goodsSpecValues.add(goodsSpecValue);
				break;
			}
		}
		goodsSku = new GoodsSku();
		goodsSku.setGoods(goods);
		return "goods-sku/edit";
	}

	/**
	 * 只可在保存时手动维护一次库存
	 */
	public String create() {
		StringBuilder specNameSb = new StringBuilder();
		StringBuilder idSb = new StringBuilder();
		if(goodsSpecValues != null){
			Iterator<GoodsSpecValue> iterator = goodsSpecValues.iterator();
			while (iterator.hasNext()) {
				GoodsSpecValue goodsSpecValue = (GoodsSpecValue) iterator.next();
				specNameSb.append(goodsSpecValue.getGoodsSpec().getSpecClass().getName()+":"+goodsSpecValue.getSpecName());
				idSb.append(goodsSpecValue.getGoodsSpec().getSpecClass().getId()+":"+goodsSpecValue.getId());
				if(iterator.hasNext()){
					specNameSb.append(";");
					idSb.append(";");
				}
			}
		}
		if("1".equals(isLock)){
			goodsSku.setState((byte)0);
		}else{
			goodsSku.setState(goodsModel.get(goodsSku.getGoods().getId()).getState());
		}
		goodsSku.setSpecName(specNameSb.toString());
		goodsSku.setSpecId(idSb.toString());
		GoodsSku goodsSkuTmp = goodsSkuModel.save(goodsSku);
		if(goodsSkuTmp == null){
			return Render.json(new DialogBean("300", "已存在该规格组合的sku",""));
		}else{
			return Render.json(new DialogBean("200", "创建成功","goods_sku", "closeCurrent"));
		}
	}

	public String edit() {
		goodsSku = goodsSkuModel.get(id);
		goodsSpecs = goodsSpecModel.findByGoods(goodsSku.getGoods());
		String specId = goodsSku.getSpecId();
		goodsSpecValues = new ArrayList<GoodsSpecValue>();
		
		
		goodsSpecValues = new ArrayList<GoodsSpecValue>();
		Iterator<GoodsSpec> goodsSpecIterator = goodsSpecs.iterator();
		while (goodsSpecIterator.hasNext()) {
			GoodsSpec goodsSpec = (GoodsSpec) goodsSpecIterator.next();
			boolean isAdded = false;
			if(!"".equals(specId)){
				String[] classValueArray = specId.split(";");
				for (String classValue : classValueArray) {
					String[] classValueMap = classValue.split(":");
					String key = classValueMap[0];
					String value = classValueMap[1];
					if(key.equals(String.valueOf(goodsSpec.getSpecClass().getId()))){
						Iterator<GoodsSpecValue> specValueIterator = goodsSpec.getGoodsSpecValue().iterator();
						while (specValueIterator.hasNext()) {
							GoodsSpecValue goodsSpecValue = (GoodsSpecValue) specValueIterator.next();
							if(value.equals(String.valueOf(goodsSpecValue.getId()))){
	//							goodsSpecValue.setId(0);
	//							goodsSpecValue.setSpecName("");
								goodsSpecValues.add(goodsSpecValue);
								isAdded = true;
								break;
							}
						}
					}
				}
			}
			if(!isAdded){
				Iterator<GoodsSpecValue> specValueIterator = goodsSpec.getGoodsSpecValue().iterator();
				while (specValueIterator.hasNext()) {
					GoodsSpecValue goodsSpecValue = (GoodsSpecValue) specValueIterator.next();
					goodsSpecValue.setId(0);
					goodsSpecValue.setSpecName("");
					goodsSpecValues.add(goodsSpecValue);
					isAdded = true;
					break;
				}
			}
		}
		
		
		
		
//		if(!"".equals(specId)){
//			String[] classValueArray = specId.split(";");
//			
//			for (String classValue : classValueArray) {
//				String[] classValueMap = classValue.split(":");
//				String key = classValueMap[0];
//				String value = classValueMap[1];
//				Iterator<GoodsSpec> iterator = goodsSpecs.iterator();
//				while (iterator.hasNext()) {
//					GoodsSpec goodsSpec = (GoodsSpec) iterator.next();
//					if(key.equals(String.valueOf(goodsSpec.getSpecClass().getId()))){					
//						Iterator<GoodsSpecValue> specValueIterator = goodsSpec.getGoodsSpecValue().iterator();
//						while (specValueIterator.hasNext()) {
//							GoodsSpecValue goodsSpecValue = (GoodsSpecValue) specValueIterator.next();
//							if(value.equals(String.valueOf(goodsSpecValue.getId()))){
//								goodsSpecValues.add(goodsSpecValue);
//							}
//						}
//					}
//				}
//			}
//		}
		return "goods-sku/edit";
	}

	/**
	 * 更新时不更新库存
	 */
	public String update() {
		StringBuilder specNameSb = new StringBuilder();
		StringBuilder idSb = new StringBuilder();
		if(goodsSpecValues != null){
			Iterator<GoodsSpecValue> iterator = goodsSpecValues.iterator();
			while (iterator.hasNext()) {
				GoodsSpecValue goodsSpecValue = (GoodsSpecValue) iterator.next();
				specNameSb.append(goodsSpecValue.getGoodsSpec().getSpecClass().getName()+":"+goodsSpecValue.getSpecName());
				idSb.append(goodsSpecValue.getGoodsSpec().getSpecClass().getId()+":"+goodsSpecValue.getId());
				if(iterator.hasNext()){
					specNameSb.append(";");
					idSb.append(";");
				}
			}
		}
		if("1".equals(isLock)){
			goodsSku.setState((byte)0);
		}else{
			goodsSku.setState(goodsModel.get(goodsSku.getGoods().getId()).getState());
		}
		goodsSku.setSpecName(specNameSb.toString());
		goodsSku.setSpecId(idSb.toString());
		GoodsSku goodsSkuTmp = goodsSkuModel.update(goodsSku);
		loggingModel.info(logger, "更新sku："+goodsSkuTmp.getSubTitle()+"："+goodsSkuTmp.getSpecName());
		if(goodsSkuTmp == null){
			return Render.json(new DialogBean("300", "已存在该规格组合的sku",""));
		}else{
			return Render.json(new DialogBean("200", "更新成功","goods_sku", "closeCurrent"));
		}
	}

	public String destroy() {
		String result = goodsSkuModel.delete(id);
		if(result.equals("")){
			return Render.json(new DialogBean("200","删除成功","goods_sku"));
		}else{
			return Render.json(new DialogBean("300", result,"")); 
		}
	}

	public String destroyBatch() {
		String result = goodsSkuModel.deleteBatch(ids);
		if(result.equals("")){
			return Render.json(new DialogBean("200","删除成功","goods_sku"));
		}else{
			return Render.json(new DialogBean("300", result,"")); 
		}
	}

	/**
	 * 转到库存维护界面
	 */
	public String toInventoryFlow() {
		inventoryFlow = new InventoryFlow();
		goodsSku = goodsSkuModel.get(id);
		inventoryFlow.setGoods(goodsSku.getGoods());
		inventoryFlow.setGoodsSku(goodsSku);
		return "goods-sku/inventoryflow";
	}

	public String updateInventory() {
		goodsSkuModel.updateInventory(inventoryFlow);
		return Render.json(new DialogBean("200", "更新成功","goods_sku_detail", "closeCurrent"));
	}
	
	/**
	 * 根据specid来查询是否已存在sku，查询的时候采用模糊查询即：specid+":"
	 * @param specId
	 * @return
	 */
	public String getSkuBySpec(){
		String str = goodsSkuModel.getSkuBySpec(specIdStr,goodsId)>0 ? "1": "0";
		return Render.text(str);
	}
	
	/**
	 * 根据specid来查询是否已存在sku，查询的时候采用模糊查询即：specid+":"，不包括已封存的
	 * @param specId
	 * @return
	 */
	public String getSkuBySpecNoMothBall(){
		String str = goodsSkuModel.getSkuBySpecNoMothBall(specIdStr,goodsId)>0 ? "1": "0";
		return Render.text(str);
	}
	/**
	 * 单选dialog调用
	 * @return
	 */
	public String dialog(){
		Map<String, String> searchMap = new HashMap<String, String>();
		searchMap.put("goodsId_eq_string", String.valueOf(goodsId));
		viewRequest = new ViewRequest();
		viewRequest.setParams(searchMap);
		page=goodsSkuModel.find(viewRequest);
		return "goods-sku/dialog";
	}
	/**
	 * 多选dialog调用(活动管理调用)
	 * @param isFree
	 */
	public String multipleDialog(){
		if(viewRequest==null){
		viewRequest = new ViewRequest();
		}
		page=goodsSkuModel.find(viewRequest);
		return "goods-sku/multipleDialog";
	}
	public void setIsFree(String isFree) {
		this.isFree = isFree;
	}

	public void setIsLock(String isLock) {
		this.isLock = isLock;
	}

	public void setSpecIdStr(String specIdStr) {
		this.specIdStr = specIdStr;
	}

	public void setInventoryFlow(InventoryFlow inventoryFlow) {
		this.inventoryFlow = inventoryFlow;
	}

	public void setSpecName(String[] specName) {
		this.specName = specName;
	}

	public void setSpecId(String[] specId) {
		this.specId = specId;
	}

	public void setViewRequest(ViewRequest viewRequest) {
		this.viewRequest = viewRequest;
	}

	public void setGoodsId(int goodsId) {
		this.goodsId = goodsId;
	}

	public void setGoodsSpecValues(List<GoodsSpecValue> goodsSpecValues) {
		this.goodsSpecValues = goodsSpecValues;
	}
	
	public void setGoodsSku(GoodsSku goodsSku) {
		this.goodsSku = goodsSku;
	}

	public void setId(int id) {
		this.id = id;
	}
	
	public void setIds(int[] ids) {
		this.ids = ids;
	}
	
	public String getMultipleDialogMyIds() {
		return multipleDialogMyIds;
	}

	public void setMultipleDialogMyIds(String multipleDialogMyIds) {
		this.multipleDialogMyIds = multipleDialogMyIds;
	}

	public String getMultipleDialogMyNames() {
		return multipleDialogMyNames;
	}

	public void setMultipleDialogMyNames(String multipleDialogMyNames) {
		this.multipleDialogMyNames = multipleDialogMyNames;
	}

}
